﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OPCAutomation;
using System.IO.Ports;
using System.Text.RegularExpressions;
using Chemistry.Models;
using System.Threading;
using Chemistry.Tools;

namespace Chemistry.WorkFlow
{
    /// <summary>
    /// 催化裂解工艺
    /// </summary>
    public class Catalysis : FlowBaseAll
    {
        #region 字段
        private int _sleepfast = 500;

        private int _relay_command;
        static bool _isgetoverstate1 = false;
        static bool _isgetoverstate2 = false;

        //组态数据
         double _settlingChamber_pressure_value;
         double _riserReactor_temp_value;

         double _charringTank_pressure_value;
         double _regenerator_preesure_value;
        /// <summary>
        /// //再生器温度
        /// </summary>
        double _regenerator_temp_value;
         double _flow_air_value;
         double _exCooler_level_value;

        //组态数据范围
        double _settlingChamber_pressure_max;
        double _settlingChamber_pressure_min;
        double _riserReactor_temp_max;
        double _riserReactor_temp_min;
        double _charringTank_pressure_max;
        double _charringTank_pressure_min;
        double _regenerator_preesure_max;
        double _regenerator_preesure_min;
        double _regenerator_temp_max;
        double _regenerator_temp_mix;
        double _flow_air_max;
        double _flow_air_min;
        double _exCooler_level_limit;//最高临界值-最大容量
        double _exCooler_level_max;//最大值
        double _exCooler_level_warning;//警告值
        /// <summary>
        /// 是否进入再生阶段
        /// </summary>
        private bool _isInRegenerate;

        //增减量
        double _settlingChamber_pressure_increment;
        double _settlingChamber_pressure_decrement;
        double _riserReactor_temp_increment;
        double _riserreactor_temp_decrement;
        double _charringTank_pressure_increment;
        double _charringTank_pressure_decrement;
        double _regenerator_preesure_increment;
        double _regenerator_preesure_decrement;
        double _regenerator_temp_increment;
        double _regenerator_temp_decrement;
        double _flow_air_increment;
        double _flow_air_decrement;
        double _exCooler_level_increment;
        double _exCooler_level_decrement;
        

        //命令
        private Tool.FlowCommand _flowcommand;
        string _prefix1 = string.Empty;
        string _prefix2 = string.Empty;
        string _llcmd = string.Empty;
        string _ywcmd = string.Empty;
        string _ylcmd = string.Empty;
        string _wdcmd = string.Empty;
        string _aicmd = string.Empty;
        string _relaycmd = string.Empty;
        int _warningnumber = 0;
        int _fognumber = 0;
        int _stirnumber1;
        int _stirnumber2;
        //开关
        private int open;
        private int close;
        #endregion

        #region 组态开关状态
        /// <summary>
        /// 汽提蒸汽阀门状态
        /// </summary>
        private bool _valveInStrippedVaporState;
        /// <summary>
        /// 催化剂阀门状态
        /// </summary>
        private bool _valveInCatalystState;
        /// <summary>
        /// 混合油阀门状态
        /// </summary>
        private bool _valveInMixedOilState;
        /// <summary>
        /// 水蒸气阀门状态
        /// </summary>
        private bool _valveInSteamState;
        /// <summary>
        /// 汽提催化剂阀门状态
        /// 待生滑阀
        /// </summary>
        private bool _valveStrippedCatalystState;
        /// <summary>
        /// 来自主风机的阀门状态
        /// </summary>
        private bool _valveInAirState;
        /// <summary>
        /// 再生催化剂流入提升反应器阀门状态
        /// 再生滑阀
        /// </summary>
        private bool _valveRiserReactorCatalystState;
        /// <summary>
        /// 再生催化剂流入烧焦罐阀门状态
        /// 循环滑阀
        /// </summary>
        private bool _valveCharringTankCatalystState;
        /// <summary>
        /// 再生催化剂流入外取热器阀门状态-暂时不用
        /// </summary>
        private bool _valveExternalCoolerCatalystState;
        /// <summary>
        /// 再生催化剂从外取热器流入烧焦罐阀门状态
        /// 外取热器下滑阀
        /// </summary>
        private bool _valveRegCatalystState;
        /// <summary>
        /// 开工燃料油阀门状态
        /// </summary>
        private bool _valveInFuelOilState;
        /// <summary>
        /// 冷却水阀门状态
        /// </summary>
        private bool _valveInColdState;
        /// <summary>
        /// 引风机阀门状态
        /// </summary>
        private bool _valveDraftFanState;
        #endregion

        #region OPCItem
        //阀门
        OPCItem _valveInStrippedVaporItem; //汽提蒸汽阀门
        OPCItem ValveInCatalyst_item;//催化剂阀门
        OPCItem ValveInMixedOil_item;//混合油阀门
        OPCItem ValveInSteam_item;//水蒸气阀门
        OPCItem ValveStrippedCatalyst_item; //汽提催化剂阀门
        OPCItem ValveInAir_item;//空气阀门
        OPCItem ValveRiserReactorCatalyst_item;// 再生催化剂流入提升反应器阀门-再生滑阀
        OPCItem ValveCharringTankCatalyst_item;//再生催化剂流入烧焦罐阀门
        OPCItem ValveExternalCoolerCatalyst_item;//再生催化剂流入外取热器阀门
        OPCItem ValveRegCatalyst_item;// 再生催化剂从外取热器流入烧焦罐阀门
        OPCItem ValveInFuelOil_item;//开工燃料油阀门
        OPCItem ValveInCold_item;//冷却水阀门
        OPCItem ValveDraftFan_item;//引风机阀门


        //管道
        OPCItem FlowStrippedVapor_item; //汽提蒸汽管道
        OPCItem FlowInCatalyst_item;//催化剂原料管道
        OPCItem FlowInMixedOil_item;//混合油原料管道
        OPCItem FlowStrippedCatalyst_item;//汽提催化剂管道
        OPCItem FlowInAir_item;//空气管道
        OPCItem FlowRiserReactorCatalyst_item;//再生催化剂流入提升反应器管道
        OPCItem FlowCharringTankCatalyst_item;//再生催化剂流入烧焦罐管道
        OPCItem FlowExternalCoolerCatalyst_item;//再生催化剂流入外取热管道
        OPCItem FlowRegCatalyst_item;//再生催化剂从外取热器流入烧焦器
        OPCItem FlowInSteam_item; //水蒸汽
        OPCItem FlowInFuelOil_item;//燃料油管道
        OPCItem FlowInCold_item;//冷却水管道
        OPCItem FlowOutAir_item;//引风机管道
        //标签
        OPCItem LabelPressureSettlingChamber_item;//沉降室压力
        OPCItem LabelPressureCharringTank_item;//烧焦罐压力
        OPCItem LabelTempRiserReactor_item;//提升管反应器温度
        OPCItem LabelFlowAir_item;
        OPCItem LabelTempRegenerator_item;//再生器温度
        OPCItem LabelPressureRegenerator_item;//再生器压力
        OPCItem LabelLevel_item;//外取热器液位
        //闪烁
        OPCItem FlashPressureSettlingChamber_item;
        OPCItem FlashlPressureCharringTank_item;
        OPCItem FlashTempRiserReactor_item;
        OPCItem FlashFlowAir_item;
        OPCItem FlashTempRegenerator_item;
        OPCItem FlashPressureRegenerator_item;
        OPCItem FlashPressurExCooler_item;
        private OPCItem _flashWarningItem;//预警闪烁



        #endregion

        #region 初始化
        public Catalysis(OPCServer opcserver, SerialPort port, bool isinner)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;
            InitFiled();
            InitOPC();
            InitOPCItem();
            InitSignal();

        }
        private void InitFiled()
        {
            _settlingChamber_pressure_value = 0;
            _riserReactor_temp_value = 220;
            _charringTank_pressure_value = 0;
            _regenerator_preesure_value = 0.00;
            _regenerator_temp_value = 220;
            _flow_air_value = 0;
            _exCooler_level_value = 0;
            


            _settlingChamber_pressure_increment = 0.01;
            _settlingChamber_pressure_decrement = 0.01;
            _riserReactor_temp_increment = 10;
            _riserreactor_temp_decrement = 5;
            _charringTank_pressure_increment = 0.01;
            _charringTank_pressure_decrement = 0.01;
            _charringTank_pressure_increment = 0.01;
            _charringTank_pressure_decrement = 0.01;
            _regenerator_preesure_increment = 0.01;
            _riserreactor_temp_decrement = 0.01;
            _regenerator_temp_increment = 10;
            _riserreactor_temp_decrement = 5;
            _flow_air_increment = 5;
            _flow_air_decrement = 5;
            _exCooler_level_increment = 5;
            _exCooler_level_decrement = 1;


            _settlingChamber_pressure_max = 0.4;
            _settlingChamber_pressure_min = 0.13;
            _riserReactor_temp_max = 530;
            _riserReactor_temp_min = 480;
            _regenerator_preesure_max = 0.6;
            _regenerator_preesure_min = 0.1;
            _regenerator_temp_max = 730;
            _regenerator_temp_mix = 600;
            _flow_air_max = 1350;
            _flow_air_min = 1280;
            _exCooler_level_max = 700;
            _exCooler_level_warning = 620;
            _exCooler_level_limit = 600;
            _charringTank_pressure_max = 0.6;
            _charringTank_pressure_min = 0.4;
        }

        private void InitOPCItem()
        {
            _valveInStrippedVaporItem = GetItem(FieldName.ValveInStrippedVapor); _valveInStrippedVaporItem.Close();
            ValveInCatalyst_item = GetItem(FieldName.ValveInCatalyst); ValveInCatalyst_item.Close();
            ValveInSteam_item = GetItem(FieldName.ValveInSteam); ValveInCatalyst_item.Close();
            ValveStrippedCatalyst_item = GetItem(FieldName.ValveStrippedCatalyst); ValveStrippedCatalyst_item.Close();
            ValveInAir_item = GetItem(FieldName.ValveInAir); ValveInAir_item.Close();
            ValveRiserReactorCatalyst_item = GetItem(FieldName.ValveRiserReactorCatalyst); ValveRiserReactorCatalyst_item.Close();
            ValveCharringTankCatalyst_item = GetItem(FieldName.ValveCharringTankCatalyst); ValveCharringTankCatalyst_item.Close();
            ValveExternalCoolerCatalyst_item = GetItem(FieldName.ValveExternalCoolerCatalyst); ValveExternalCoolerCatalyst_item.Close();
            ValveRegCatalyst_item = GetItem(FieldName.ValveRegCatalyst); ValveRegCatalyst_item.Close();
            ValveDraftFan_item = GetItem(FieldName.ValveDraftFan); ValveDraftFan_item.Close();
            ValveInFuelOil_item = GetItem(FieldName.ValveInFuelOil); ValveInFuelOil_item.Close();
            ValveInCold_item = GetItem(FieldName.ValveInCold); ValveInCold_item.Close();
            ValveDraftFan_item = GetItem(FieldName.ValveDraftFan); ValveDraftFan_item.Close();

            FlowStrippedVapor_item = GetItem(FieldName.FlowStrippedVapor); FlowStrippedVapor_item.Close();
            FlowInCatalyst_item = GetItem(FieldName.FlowInCatalyst); FlowInCatalyst_item.Close();
            FlowInMixedOil_item = GetItem(FieldName.FlowInMixedOil); FlowInMixedOil_item.Close();
            FlowStrippedCatalyst_item = GetItem(FieldName.FlowStrippedCatalyst); FlowInCatalyst_item.Close();
            FlowInAir_item = GetItem(FieldName.FlowInAir); FlowInAir_item.Close();
            FlowRiserReactorCatalyst_item = GetItem(FieldName.FlowRiserReactorCatalyst); FlowRiserReactorCatalyst_item.Close();
            FlowCharringTankCatalyst_item = GetItem(FieldName.FlowCharringTankCatalyst); FlowCharringTankCatalyst_item.Close();
            FlowExternalCoolerCatalyst_item = GetItem(FieldName.FlowExternalCoolerCatalyst); FlowExternalCoolerCatalyst_item.Close();
            FlowRegCatalyst_item = GetItem(FieldName.FlowRegCatalyst); FlowRegCatalyst_item.Close();
            FlowInSteam_item = GetItem(FieldName.FlowInSteam); FlowInSteam_item.Close();
            FlowOutAir_item = GetItem(FieldName.FlowOutAir); FlowOutAir_item.Close();
            FlowInFuelOil_item = GetItem(FieldName.FlowInFuelOil); FlowInFuelOil_item.Close();
            FlowInCold_item = GetItem(FieldName.FlowInCold); FlowInCold_item.Close();

            LabelPressureSettlingChamber_item = GetItem(FieldName.LabelPressureSettlingChamber); LabelPressureSettlingChamber_item.Write(_settlingChamber_pressure_value);
            LabelPressureCharringTank_item = GetItem(FieldName.LabelPressureCharringTank); LabelPressureCharringTank_item.Write(_charringTank_pressure_value);
            LabelTempRiserReactor_item = GetItem(FieldName.LabelTempRiserReactor); LabelTempRiserReactor_item.Write(_riserReactor_temp_value);
            LabelFlowAir_item = GetItem(FieldName.LabelFlowAir); LabelFlowAir_item.Write(_flow_air_value);
            LabelTempRegenerator_item = GetItem(FieldName.LabelTempRegenerator); LabelTempRegenerator_item.Write(_regenerator_temp_value);
            LabelPressureRegenerator_item = GetItem(FieldName.LabelPressureRegenerator); LabelPressureRegenerator_item.Write(_regenerator_preesure_value);
            LabelLevel_item = GetItem(FieldName.LabelLevel); LabelLevel_item.Write(_exCooler_level_value);

            FlashPressureSettlingChamber_item = GetItem(FieldName.FlashPressureSettlingChamber); FlashPressureSettlingChamber_item.Close();
            FlashlPressureCharringTank_item = GetItem(FieldName.FlashlPressureCharringTank); FlashlPressureCharringTank_item.Close();
            FlashTempRiserReactor_item = GetItem(FieldName.FlashTempRiserReactor); FlashTempRiserReactor_item.Close();
            FlashFlowAir_item = GetItem(FieldName.FlashFlowAir); FlashFlowAir_item.Close();
            FlashTempRegenerator_item = GetItem(FieldName.FlashTempRegenerator); FlashTempRegenerator_item.Close();
            FlashPressureRegenerator_item = GetItem(FieldName.FlashPressureRegenerator); FlashPressureRegenerator_item.Close();
            FlashPressurExCooler_item = GetItem(FieldName.FlashPressurExCooler); FlashPressurExCooler_item.Close();
            _flashWarningItem = GetItem(FieldName.FlashWarning);_flashWarningItem.Close();
            
        }


        private async Task InitServerData()
        {
            _details = await GetDetailList(GetType().Name);
        }

        private void InitSignal()
        {
            if (Isinner)
            {
                open = 1;
                close = 0;
                ListenSignal();

            }
            else
            {
                InitFlowCommandData();
                _serialPort.DataReceived += _serialPort_DataReceived;
                InitOpcItemWithSerialPort();
                ListenSerialPort();
                open = 48;
                close = 49;
            }

        }


        #region InitSignal
        private void ListenSignal()
        {
            Task t = new Task(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    int valveInStrippedVapor = Convert.ToInt32(ReadItem(FieldName.ValveInStrippedVapor));
                    int valveInCatalyst = Convert.ToInt32(ReadItem(FieldName.ValveInCatalyst));
                    int valveInMixedOil = Convert.ToInt32(ReadItem(FieldName.ValveInMixedOil));
                    int valveInSteam = Convert.ToInt32(ReadItem(FieldName.ValveInSteam));
                    int valveStrippedCatalyst = Convert.ToInt32(ReadItem(FieldName.ValveStrippedCatalyst));
                    int valveInAir = Convert.ToInt32(ReadItem(FieldName.ValveInAir));
                    int valveRiserReactorCatalyst = Convert.ToInt32(ReadItem(FieldName.ValveRiserReactorCatalyst));
                    int valveCharringTankCatalyst = Convert.ToInt32(ReadItem(FieldName.ValveCharringTankCatalyst));
                    int valveExternalCoolerCatalyst = Convert.ToInt32(ReadItem(FieldName.ValveExternalCoolerCatalyst));
                    int valveRegCatalyst = Convert.ToInt32(ReadItem(FieldName.ValveRegCatalyst));
                    int valveInFuelOil = Convert.ToInt32(ReadItem(FieldName.ValveInFuelOil));
                    int valveInCold = Convert.ToInt32(ReadItem(FieldName.ValveInCold));
                    int valveDraftFan = Convert.ToInt32(ReadItem(FieldName.ValveDraftFan));

                    _valveInStrippedVaporState = valveInStrippedVapor == open;
                    _valveInCatalystState = valveInCatalyst == open;
                    _valveInMixedOilState = valveInMixedOil == open;
                    _valveInSteamState = valveInSteam == open;
                    _valveStrippedCatalystState = valveStrippedCatalyst == open;
                    _valveInAirState = valveInAir == open;
                    _valveRiserReactorCatalystState = valveRiserReactorCatalyst == open;
                    _valveCharringTankCatalystState = valveCharringTankCatalyst == open;
                    _valveExternalCoolerCatalystState = valveExternalCoolerCatalyst == open;
                    _valveRegCatalystState = valveRegCatalyst == open;
                    _valveInFuelOilState = valveInFuelOil == open;
                    _valveInColdState = valveInCold == open;
                    _valveDraftFanState = valveDraftFan == open;

                    DateTime dnow = DateTime.Now;
                    Step step = new Step()
                    {
                        Status =
                        {
                            {StatusName.汽提蒸汽阀门,valveInStrippedVapor },
                            {StatusName.催化剂阀门,valveInCatalyst },
                            {StatusName.混合油阀门,valveInMixedOil},
                            {StatusName.水蒸气阀门,valveInSteam },
                            {StatusName.空气阀门_主风机_右,valveInAir },
                            {StatusName.再生催化剂流入提升反应器阀门_再生滑阀,valveRiserReactorCatalyst},
                            {StatusName.再生催化剂流入烧焦罐阀门,valveCharringTankCatalyst },
                            {StatusName.再生催化剂流入外取热器阀门,valveExternalCoolerCatalyst},
                            {StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀,valveRegCatalyst },
                            {StatusName.沉降室流入烧焦罐阀门_待生滑阀,valveStrippedCatalyst},
                            {StatusName.沉降室压力,_settlingChamber_pressure_value},
                            {StatusName.提升管反应器温度,_riserReactor_temp_value },
                            {StatusName.再生器压力,_regenerator_preesure_value },
                            {StatusName.再生器温度,_regenerator_temp_value},
                            {StatusName.烧焦罐压力,_charringTank_pressure_value},
                            {StatusName.外取热器液位,_exCooler_level_value },
                            { StatusName.主风机流量,_flow_air_value},
                            { StatusName.燃料油阀门,valveInFuelOil},
                            { StatusName.冷却水阀门,valveInCold},
                             { StatusName.引风机阀门,valveDraftFan},
                             {StatusName.是否进入再生阶段,  _isInRegenerate?1:0}//进入：1
                        },
                        Date = dnow,

                    };
                    _steps.Add(step);
                    _isListenSingnalover = true;
                    Thread.Sleep(_sleepfast);
                }


            });

            t.Start();
        }

        private void InitFlowCommandData()
        {
            _flowcommand = Tools.Tool.GetFlowCommand(this.GetType().Name);
            _prefix1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix1").Value;
            _prefix2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix2").Value;
            _llcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "llcmd").Value;
            _ywcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ywcmd").Value;
            _ylcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ylcmd").Value;
            _wdcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "wdcmd").Value;
            _aicmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "aicmd").Value;
            _relaycmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "relaycmd").Value;
            _warningnumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning").Value);
            _fognumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "fog").Value);
            _stirnumber1 = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "stir1").Value);
            _stirnumber2 = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "stir2").Value);
        }

        private int valveInStrippedVapor,
            valveInCatalyst,
            valveInMixedOil,
            valveInSteam,
            valveInAir,
            valveRiserReactorCatalyst,
            valveCharringTankCatalyst,
            valveExternalCoolerCatalyst,
            valveRegCatalyst,
            valveStrippedCatalyst,
            valveInFuelOil,
            valveInCold,
            valveDraftFan;
        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string data = _serialPort.ReadLine();
                Console.WriteLine("收到：" + data);

                    #region 165

            Match match = Regex.Match(data, @"\d{5}_\d{3}");
            if (match.Success)
            {
                string s = match.Groups[0].Value.Split('_')[1];
                int v = Convert.ToInt32(s);
                string r = Convert.ToString(v, 2).PadLeft(8, '0');
                string first = match.Groups[0].Value.Split('_')[0];

                if (first == _prefix1)
                {
                    valveInSteam = Convert.ToInt32(r[0]);
                    valveInStrippedVapor = Convert.ToInt32(r[1]);
                    valveStrippedCatalyst = Convert.ToInt32(r[2]);
                    valveInCatalyst = Convert.ToInt32(r[3]);
                    valveRegCatalyst = Convert.ToInt32(r[4]);
                    valveInCold = Convert.ToInt32(r[5]);
                    valveInMixedOil = Convert.ToInt32(r[6]);
                    valveCharringTankCatalyst = Convert.ToInt32(r[7]);

                    _valveInSteamState = valveInSteam==open;
                    _valveInStrippedVaporState = valveInStrippedVapor == open;
                    _valveStrippedCatalystState = valveStrippedCatalyst == open;
                    _valveInCatalystState = valveInCatalyst == open;
                    _valveRegCatalystState = valveRegCatalyst == open;
                    _valveInColdState = valveInCold == open;
                    _valveInMixedOilState = valveInMixedOil == open;
                    _valveCharringTankCatalystState = valveCharringTankCatalyst == open;
                    _isgetoverstate1 = true;

                }
                else if (first == _prefix2)
                {
                    valveInAir  = Convert.ToInt32(r[4]);//right
                    valveDraftFan = Convert.ToInt32(r[5]);//left
                    valveRiserReactorCatalyst = Convert.ToInt32(r[6]);
                    valveInFuelOil = Convert.ToInt32(r[7]);

                    _valveDraftFanState = valveDraftFan == open;
                    _valveInAirState = valveInAir == open;
                    _valveRiserReactorCatalystState = valveRiserReactorCatalyst == open;
                    _valveInFuelOilState = valveInFuelOil == open;

                    _isgetoverstate2 = true;
                }

            }
            #endregion

            #region 添加步骤

            DateTime now = DateTime.Now;
            Step step = new Step()
            {
                Status =
                        {
                            {StatusName.汽提蒸汽阀门,valveInStrippedVapor },
                            {StatusName.催化剂阀门,valveInCatalyst },
                            {StatusName.混合油阀门,valveInMixedOil},
                            {StatusName.水蒸气阀门,valveInSteam },
                            {StatusName.空气阀门_主风机_右,valveInAir },
                            {StatusName.再生催化剂流入提升反应器阀门_再生滑阀,valveRiserReactorCatalyst},
                            {StatusName.再生催化剂流入烧焦罐阀门,valveCharringTankCatalyst },
                            {StatusName.再生催化剂流入外取热器阀门,valveExternalCoolerCatalyst},
                            {StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀,valveRegCatalyst },
                            {StatusName.沉降室流入烧焦罐阀门_待生滑阀,valveStrippedCatalyst},
                            {StatusName.沉降室压力,_settlingChamber_pressure_value},
                            {StatusName.提升管反应器温度,_riserReactor_temp_value },
                            {StatusName.再生器压力,_regenerator_preesure_value },
                            {StatusName.再生器温度,_regenerator_temp_value},
                            {StatusName.烧焦罐压力,_charringTank_pressure_value},
                            {StatusName.外取热器液位,_exCooler_level_value },
                            { StatusName.主风机流量,_flow_air_value},
                            { StatusName.燃料油阀门,valveInFuelOil},
                            { StatusName.冷却水阀门,valveInCold},
                             { StatusName.引风机阀门,valveDraftFan},
                             {StatusName.是否进入再生阶段,  _isInRegenerate?1:0}//进入：1
                        },
                Date = now,

            };
            _steps.Add(step);

            #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
           

        
        }
        private void ListenSerialPort()
        {
            string chkcmd_1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd1").Value; // "#RYW21651&";
            string chkcmd_2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd2").Value; //"#RYW21652&";


            Task listSerialPortState = new Task(
                () =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        SendScannerCmd(chkcmd_1);
                        SendScannerCmd(chkcmd_2);
                    }
                });
            listSerialPortState.Start();
        }
        void SendScannerCmd(string cmd)
        {
            try
            {
                if (!_serialPort.IsOpen) return;
                lock (this)
                {
                    Thread.Sleep(120);
                    _serialPort.Write(cmd);
                }
            }
            catch (Exception)
            {
            }
        }
        #endregion

        private void InitOpcItemWithSerialPort()
        {
            SpSettlingChamberPressure(_settlingChamber_pressure_value);
            SpReactorPressureValue(_regenerator_preesure_value);
            SpReactorTemp(_regenerator_temp_value);
            SpRiserReactorTemp(_riserReactor_temp_value);
            WriteFlowValue(_llcmd, 1, _flow_air_value);
            SPWriteTool(_relay_command);
            SPYWValue(_exCooler_level_value);
        }

        #endregion

        #region 重写公共方法

        public override void Begin()
        {
            ListenOPCRelation();
        }
        bool _isListenSingnalover;
        public override async Task<string> CheckDefault()
        {
            StringBuilder builder = new StringBuilder();
            if (_valveInStrippedVaporState)
                builder.AppendLine("汽提蒸汽阀门未关闭");
            if(_valveInCatalystState)
                builder.AppendLine("催化剂阀门未关闭");
            if (_valveInMixedOilState)
                builder.AppendLine("混合油阀门未关闭");
            if (_valveInSteamState)
                builder.AppendLine("水蒸气阀门未关闭");
            if (_valveStrippedCatalystState)
                builder.AppendLine("待生滑阀未关闭");
            if (_valveInAirState)
                builder.AppendLine("主风机未关闭");
            if (_valveRiserReactorCatalystState)
                builder.AppendLine("再生滑阀未关闭");
            if (_valveCharringTankCatalystState)
                builder.AppendLine("循环滑阀未关闭");
            if (_valveRegCatalystState)
                builder.AppendLine("外取热器下滑阀未关闭");
            if (_valveInFuelOilState)
                builder.AppendLine("开工燃料油阀门未关闭");
            if (_valveInColdState)
                builder.AppendLine("冷却水阀门未关闭");
            if (_valveDraftFanState)
                builder.AppendLine("引风机阀门未关闭");
            bool isOvertime = false;
            var loop = 0;

            await Task.Run(() =>
            {
                if (!Isinner)
                {
                    while (!_isgetoverstate1 || !_isgetoverstate2)
                    {
                        Thread.Sleep(1000);
                        loop++;
                        if (loop > 30)
                        {
                            isOvertime = true;
                            break;
                        }
                    }
                }
                else
                {
                    while (!_isListenSingnalover)
                    {
                        Thread.Sleep(1000);
                    }
                }


            });

            await InitServerData();
            if (_details == null)
                builder.AppendLine("可能由于网络原因，导致获取数据失败，请点击\"确定\"按钮 尝试重新获取");

            if (!isOvertime) return builder.ToString();
            builder.Clear();
            builder.AppendLine("访问设备信号超时，请检查设备连接");
            return builder.ToString();
        }

        public override void Close()
        {
            this._listenCts.Cancel();
            base.Close();
            if (_serialPort != null)
            {
                _serialPort.DataReceived -= _serialPort_DataReceived;
                _serialPort.Close();
            }
        }

        public override void Over()
        {
            Close();
            CalcFlowAndStep();
            Score = CalcScore();
            CloseAllRelay();
            Finish();

        }

        private void ListenOPCRelation()
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                #region 反应系统

                #region  催化剂经再生器高温处理，开工炉打开

                #region 燃料油进入，开工  -烧焦罐压力/再生器温度->改成再生器压力
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInFuelOilState)
                        {
                            if (!Isinner)
                                ValveInFuelOil_item.Open();
                            FlowInFuelOil_item.StartFlow();
                            //烧焦罐压力范围[0.3-0.7]  实际[0.4-0.6]
                            //_charringTank_pressure_increment = _charringTank_pressure_value > 0.4 ? 0 : 0.005;
                            //_charringTank_pressure_value += _charringTank_pressure_increment;
                            //LabelPressureCharringTank_item.Write(_charringTank_pressure_value);
                            //再生器温度
                            _regenerator_preesure_increment = _regenerator_preesure_value > 0.4 ? 0 : 0.005;
                            _regenerator_preesure_value += _regenerator_preesure_increment;
                            LabelPressureRegenerator_item.Write(_regenerator_preesure_value);
                            SpReactorPressureValue(_regenerator_preesure_value);
                            //再生器温度[450-600] 实际[500-550]
                            _regenerator_temp_increment = _regenerator_temp_value > 550 ? 0 : 1;
                            _regenerator_temp_value += _regenerator_temp_increment;
                            LabelTempRegenerator_item.Write(_regenerator_temp_value);
                            SpReactorTemp(_regenerator_temp_value);
                        }
                        else
                        {
                            if (!Isinner)
                                ValveInFuelOil_item.Close();
                            FlowInFuelOil_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion
                #region 空气进入,助燃，-再生器温度
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInAirState)
                        {
                            if (!Isinner)
                                ValveInAir_item.Open();
                            FlowInAir_item.StartFlow();
                            //BeginStir(Fan.right);
                            BeginRightStir();
                            if (_isInRegenerate) //进入再生阶段
                            {
                                if (_flow_air_value < 1000)
                                    _flow_air_increment = 20;
                                else if (_flow_air_value >= 1000 && _flow_air_value<=1300)
                                    _flow_air_increment = 3;
                                else
                                    _flow_air_increment = 0;

                                _flow_air_value += _flow_air_increment;
                                LabelFlowAir_item.Write(_flow_air_value);
                                WriteFlowValue(_llcmd, 1, _flow_air_value);
                                //再生器温度升高，进行油焦分解
                                if (_regenerator_temp_value < 450)
                                    _regenerator_temp_increment = 5;
                                else if (_regenerator_temp_value >= 450 && _regenerator_temp_value <= 730)
                                    _regenerator_temp_increment = 3;
                                else
                                    _regenerator_temp_increment = 0;
                                _regenerator_temp_value += _regenerator_temp_increment;
                                LabelTempRegenerator_item.Write(_regenerator_temp_value);
                                SpReactorTemp(_regenerator_temp_value);
                            }

                            else//预热阶段
                            {
                                //主风机流量[1000 - 1400] 实际[1280 - 1350]
                                //主风机流量[300-600]  实际[1280-1350]*(30%-40%)=[380-550]
                                if (_flow_air_value < 300)
                                    _flow_air_increment =5;
                                else if (_flow_air_value >= 300 && _flow_air_value <= 600)
                                    _flow_air_increment = 3;
                                else
                                    _flow_air_increment = 0;
                                _flow_air_value += _flow_air_increment;
                                LabelFlowAir_item.Write(_flow_air_value);
                                WriteFlowValue(_llcmd, 1, _flow_air_value);
                                //再生器温度[450-600] 实际[500-550]
                                _regenerator_temp_increment = _regenerator_temp_value > 550 ? 0 : 2;
                                _regenerator_temp_value += _regenerator_temp_increment;
                                LabelTempRegenerator_item.Write(_regenerator_temp_value);
                                SpReactorTemp(_regenerator_temp_value);
                            }
                        }
                        else
                        {
                            if (!Isinner)
                                ValveInAir_item.Close();
                            FlowInAir_item.StopFlow();
                            //StopStir(Fan.right);
                            StopRightStir();
                        }
                        Thread.Sleep(_sleepfast);

                    }
                });
                #endregion
                #region 冷却水进入外取热器-液位
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInColdState)
                        {
                            if (!Isinner)
                                ValveInCold_item.Open();
                            FlowInCold_item.StartFlow();
                            //外取热器液位[40%-60%]->
                            _exCooler_level_increment = _exCooler_level_value < _exCooler_level_max ? 3 : 0;
                            _exCooler_level_value += _exCooler_level_increment;
                            

                            if (_exCooler_level_value <= _exCooler_level_limit)
                            {
                                SPYWValue(_exCooler_level_value);
                                LabelLevel_item.Write(_exCooler_level_value);
                            }
                            else if(_exCooler_level_value>_exCooler_level_warning)
                            {
                                BeginWarning(WarningType.液位过高);
                                _exCooler_level_value = _exCooler_level_limit;
                            }
                        }
                        else
                        {
                            if (!Isinner)
                                ValveInCold_item.Close();
                            FlowInCold_item.StopFlow();

                            StopWarning(WarningType.液位过高);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 催化剂进入再生器 -升温-500以上催化剂起作用
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInCatalystState)
                        {
                            if (!Isinner)
                                ValveInCatalyst_item.Open();
                            FlowInCatalyst_item.StartFlow();
                            //再生器温度[500-800] 实际[600-730]
                            _regenerator_temp_increment = _regenerator_temp_value > 800 ? 0 : 3;
                            _regenerator_temp_value += _regenerator_temp_increment;
                            LabelTempRegenerator_item.Write(_regenerator_temp_value);
                            SpReactorTemp(_regenerator_temp_value);

                        }
                        else
                        {
                            if (!Isinner)
                                ValveInCatalyst_item.Close();
                            FlowInCatalyst_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }

                });

                #endregion
                #endregion

                #region 油料进入提升管反应器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInMixedOilState)
                        {
                            if (!Isinner) ValveInMixedOil_item.Open();
                            FlowInMixedOil_item.StartFlow();
                            //油料进入,提升管温度上升[350-550] 实际[400-500]
                            //_riserReactor_temp_increment = _riserReactor_temp_value < 350 ? 5 : 3;
                            //_riserReactor_temp_increment = _riserReactor_temp_value > 550 ? 0 : 3;
                            //_riserReactor_temp_value += _riserReactor_temp_increment;
                            //LabelTempRiserReactor_item.Write(_riserReactor_temp_value);

                        }
                        else
                        {
                            if (!Isinner)
                                ValveInMixedOil_item.Close();
                            FlowInMixedOil_item.StopFlow();

                        }
                        Thread.Sleep(_sleepfast);

                    }
                });
                #endregion

                #region  水蒸汽
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {

                        if (_valveInSteamState)
                        {
                            if (!Isinner)
                                ValveInSteam_item.Open();
                            FlowInSteam_item.StartFlow();
                            //提升管反应器温度继续上升,温度[350,550]  实际[400,500]
                            //_riserReactor_temp_increment = +_riserReactor_temp_value < 400 ? 5 : 3;
                            //_riserReactor_temp_increment = _riserReactor_temp_value > 500 ? 0 : 3;
                            //_riserReactor_temp_value += _riserReactor_temp_increment;
                            //LabelTempRiserReactor_item.Write(_riserReactor_temp_value);
                        }
                        else
                        {
                            if (!Isinner)
                                ValveInSteam_item.Close();
                            FlowInSteam_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }

                });

                #endregion

                #region 来自再生器的催化剂
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveRiserReactorCatalystState)
                        {
                            if (!Isinner)
                                ValveRiserReactorCatalyst_item.Open();
                            FlowRiserReactorCatalyst_item.StartFlow();
                            //催化剂从再生器流出，温度下降,范围[450-500] 实际[500-550]
                            //_regenerator_temp_decrement = _regenerator_temp_value < 550 ? 1 : 8;
                            _regenerator_temp_decrement = _regenerator_temp_value > 500 ? 1 : 0;
                            _regenerator_temp_value -= _regenerator_temp_decrement;
                            LabelTempRegenerator_item.Write(_regenerator_temp_value);
                            SpReactorTemp(_regenerator_temp_value);
                            //烧焦罐压力下降
                            //_charringTank_pressure_decrement = _charringTank_pressure_value > 0.7 ? 0.03 : 0.01;
                            //_charringTank_pressure_decrement = _charringTank_pressure_value < 0.2 ? 0 : 0.01;
                            //_charringTank_pressure_value -= _charringTank_pressure_decrement;
                            //LabelPressureCharringTank_item.Write(_charringTank_pressure_value);

                            //改成再生器压力
                            _regenerator_preesure_decrement = _regenerator_preesure_value < 0.2 ? 0 : 0.01;
                            _regenerator_preesure_value -= _regenerator_preesure_decrement;
                            LabelPressureRegenerator_item.Write(_regenerator_preesure_value);
                            SpReactorPressureValue(_regenerator_preesure_value);

                            //催化剂进入，反应开始，提升管反应器温度继续上升
                            //_riserReactor_temp_increment = +_riserReactor_temp_value < 400 ? 5 : 3;
                            //_riserReactor_temp_increment = _riserReactor_temp_value > 500 ? 0 : 3;
                            //_riserReactor_temp_value += _riserReactor_temp_increment;
                            //LabelTempRiserReactor_item.Write(_riserReactor_temp_value);
                        }
                        else
                        {
                            if (!Isinner)
                                ValveRiserReactorCatalyst_item.Close();
                            FlowRiserReactorCatalyst_item.StopFlow();

                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                //反应部分
                #region 混合油、水蒸气、催化剂-提升管反应器温度。汽提蒸汽进入，压力升高
                Task.Run(() =>
                       {
                           while (!_listenCts.IsCancellationRequested)
                           {
                               if (_valveInMixedOilState && _valveInSteamState && _valveRiserReactorCatalystState)
                               {
                                   if (_riserReactor_temp_value < 450)
                                       _riserReactor_temp_increment = 5;
                                   else if (_riserReactor_temp_value >= 450 && _riserReactor_temp_value<=550)
                                       _riserReactor_temp_increment = 2;
                                   else
                                       _riserReactor_temp_increment = 0;

                                   _riserReactor_temp_value += _riserReactor_temp_increment;
                                   LabelTempRiserReactor_item.Write(_riserReactor_temp_value);
                                   SpRiserReactorTemp(_riserReactor_temp_value);

                                   if (_riserReactor_temp_value > 400 && _valveInStrippedVaporState)
                                   {
                                       _settlingChamber_pressure_increment = _settlingChamber_pressure_value > 0.3 ? 0.005 : 0.01;
                                       _settlingChamber_pressure_value += _settlingChamber_pressure_increment;
                                       LabelPressureSettlingChamber_item.Write(_settlingChamber_pressure_value);
                                       SpSettlingChamberPressure(_settlingChamber_pressure_value);
                                       if (_settlingChamber_pressure_value > _settlingChamber_pressure_max)
                                       {
                                           FlashPressureSettlingChamber_item.StartFlow();
                                           BeginWarning(WarningType.沉降器压力过高);
                                       }
                                   }
                               }
                               Thread.Sleep(_sleepfast);
                           }
                       }); 

                #endregion


                #region 进入沉降室，汽提蒸汽进入
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInStrippedVaporState)
                        {
                            if (!Isinner)
                                _valveInStrippedVaporItem.Open();
                            FlowStrippedVapor_item.StartFlow();
                            //容量一定，气压与温度成正比
                            //500℃左右的油气,沉降室压力范围[0.1-0.3]  标准[0.13-0.2]
                            //_settlingChamber_pressure_increment = _settlingChamber_pressure_value > 0.3 ? 0 : 0.01;
                            //_settlingChamber_pressure_value += _settlingChamber_pressure_increment;
                            //LabelPressureSettlingChamber_item.Write(_settlingChamber_pressure_value);
                            //提升管温度下降
                        }
                        else
                        {
                            if (!Isinner)
                                _valveInStrippedVaporItem.Close();
                            FlowStrippedVapor_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });

                #endregion

                #region  沉降室气压（气压机调节气压？）-打开引风机，压力下降
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)//引风机降压
                    {
                        if (_valveDraftFanState)
                        {
                            if (!Isinner)
                                ValveDraftFan_item.Open();
                            FlowOutAir_item.StartFlow();
                            //BeginStir(Fan.left);
                            BeginLeftStir();
                            _settlingChamber_pressure_decrement = _settlingChamber_pressure_value < 0.1 ? 0 : 0.005;
                            _settlingChamber_pressure_value -= _settlingChamber_pressure_decrement;
                            LabelPressureSettlingChamber_item.Write(_settlingChamber_pressure_value);
                            SpSettlingChamberPressure(_settlingChamber_pressure_value);
                            if (_settlingChamber_pressure_value < 0.2)
                            {
                                FlashPressureSettlingChamber_item.StopFlow();
                                StopWarning(WarningType.沉降器压力过高);
                            }
                        }
                        else
                        {
                            if (!Isinner)
                                ValveDraftFan_item.Close();
                            FlowOutAir_item.StopFlow();
                            //StopStir(Fan.left);
                            StopLeftStir();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #endregion

                #region 再生系统

                #region 经汽提后的油焦催化剂混合物进入烧焦罐底
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveStrippedCatalystState)
                        {
                            if (!Isinner)
                                ValveStrippedCatalyst_item.Open();
                            FlowStrippedCatalyst_item.StartFlow();
                            //烧焦罐压力[0.3-0.7]  实际[0.4-0.6]

                            if (_settlingChamber_pressure_value >= 0.1)
                            {
                                //_charringTank_pressure_increment = _charringTank_pressure_value > 0.6 ? 0 : 0.005;
                                //_charringTank_pressure_value += _charringTank_pressure_increment;
                                //LabelPressureCharringTank_item.Write(_charringTank_pressure_value);
                                _regenerator_preesure_increment = _regenerator_preesure_value > 0.6 ? 0 : 0.005;
                                _regenerator_preesure_value += _regenerator_preesure_increment;
                                LabelPressureRegenerator_item.Write(_regenerator_preesure_value);
                                SpReactorPressureValue(_regenerator_preesure_value);
                            }

                          
                            if (_regenerator_preesure_value > 0.41)
                                _isInRegenerate = true;
                        }
                        else
                        {
                            if (!Isinner)
                                ValveStrippedCatalyst_item.Close();
                            FlowStrippedCatalyst_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });

                #region 外取热器(油焦催化剂混合物)流向烧焦罐底
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveRegCatalystState)
                        {
                            if (!Isinner)
                                ValveRegCatalyst_item.Open();
                            FlowRegCatalyst_item.StartFlow();
                            if (_isInRegenerate)//汽提段之后起作用
                            {                              
                                //_charringTank_pressure_increment = _charringTank_pressure_value > 0.6 ? 0 : 0.005;
                                //_charringTank_pressure_value += _charringTank_pressure_increment;
                                //LabelPressureCharringTank_item.Write(_charringTank_pressure_value);

                                _regenerator_preesure_increment = _regenerator_preesure_value > 0.6 ? 0 : 0.005;
                                _regenerator_preesure_value += _regenerator_preesure_increment;
                                LabelPressureRegenerator_item.Write(_regenerator_preesure_value);
                                SpReactorPressureValue(_regenerator_preesure_value);
                            }
                            

                            _exCooler_level_value -= 2;
                            if (_exCooler_level_value <= 0)
                                _exCooler_level_value = 0;
                            LabelLevel_item.Write(_exCooler_level_value);
                            SPYWValue(_exCooler_level_value);
                        }
                        else
                        {
                            if (!Isinner)
                                ValveRegCatalyst_item.Close();
                            FlowRegCatalyst_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);



                    }
                });
                #endregion
                #region 调节主风机风量，助燃,油焦分解-不用了
                //Task.Run(() =>
                //{
                //    while (!_listenCts.IsCancellationRequested)
                //    {
                //        if (_valveInAirState)
                //        {
                //            if (!Isinner)
                //            {
                //                ValveInAir_item.Open();
                //                //ValveStrippedCatalyst_item.Open();
                //            }
                //            FlowInAir_item.StartFlow();
                //            //FlowStrippedCatalyst_item.StopFlow();

                //            //主风机流量[1000-1400] 实际[1280-1350]
                //            if (_isInRegenerate)//进入再生阶段
                //            {
                //                _flow_air_increment = _flow_air_value < 1000 ? 15 : 3;
                //                _flow_air_increment = _flow_air_value > 1300 ? 0 : 3;
                //                _flow_air_value += _flow_air_increment;
                //                LabelFlowAir_item.Write(_flow_air_value);
                //            }
                           
                //            //再生器温度升高，进行油焦分解
                //            _regenerator_temp_increment = _regenerator_temp_value < 450 ? 5 : 3;
                //            _regenerator_temp_increment = _regenerator_temp_value > 730 ? 0 : 3;
                //            _regenerator_temp_value += _regenerator_temp_increment;
                //            LabelTempRegenerator_item.Write(_regenerator_temp_value);

                //        }
                //        else
                //        {
                //            if (!Isinner)
                //            {
                //                ValveInAir_item.Close();
                //                //ValveStrippedCatalyst_item.Close();

                //            }
                //            //FlowStrippedCatalyst_item.StopFlow();
                //            FlowInAir_item.StopFlow();
                //        }
                //        Thread.Sleep(_sleepfast);

                //    }

                //});

                #endregion



                #endregion

                #region 再生催化剂三路
                //第一路经再生斜管去提升管反应器,(油焦完成分解)
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveRiserReactorCatalystState)
                        {
                            if (!Isinner)
                                ValveRiserReactorCatalyst_item.Open();
                            FlowRiserReactorCatalyst_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                ValveRiserReactorCatalyst_item.Close();
                            FlowRiserReactorCatalyst_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }

                });
                //外取热器保持再生器内热平衡
                //第二路经外取热上斜管去外取热器，
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveExternalCoolerCatalystState)
                        {
                            if (!Isinner)
                                ValveExternalCoolerCatalyst_item.Open();
                            FlowExternalCoolerCatalyst_item.StartFlow();
                            //过热器温度过高，保持热平衡，外取热器液位相对下降
                            //if (_regenerator_temp_value > 730)
                            //{
                            //    _exCooler_level_decrement = _regenerator_temp_value > 730 ? 1 : 0;
                            //    _exCooler_level_value -= _exCooler_level_decrement;
                            //    LabelLevel_item.Write(_exCooler_level_value);

                            //}

                            //再生器温度下降
                           // _regenerator_temp_decrement = _regenerator_temp_value < 600 ? 1 : 8;
                            _regenerator_temp_decrement = _regenerator_temp_value > 600 ? 8 : 5;
                            _regenerator_temp_value -= _regenerator_temp_decrement;
                            if (_regenerator_temp_value < 0)
                                _regenerator_temp_value = 0;
                            LabelTempRegenerator_item.Write(_regenerator_temp_value);
                            SpReactorTemp(_regenerator_temp_value);

                        }
                        else
                        {
                            if (!Isinner)
                                ValveExternalCoolerCatalyst_item.Close();
                            FlowExternalCoolerCatalyst_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                //第三路经循环斜管去烧焦罐（油焦未完成分解）
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveCharringTankCatalystState)
                        {
                            if (!Isinner)
                                ValveCharringTankCatalyst_item.Open();
                            FlowCharringTankCatalyst_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                ValveCharringTankCatalyst_item.Close();
                            FlowCharringTankCatalyst_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #endregion
            });

        }

       
        private void CalcFlowAndStep()
        {
            #region 流程步骤

            //1预热准备
            //1.1 外取热器上水 40-60%->40%以上
            var level_cold_item =
                _steps.Where(i => i.Status[StatusName.冷却水阀门] == open)
                    .OrderByDescending(i => i.Status[StatusName.外取热器液位])
                    .ThenByDescending(i => i.Date)
                    .FirstOrDefault();
            //1.2 再生器压力 <0.4
            var regenerPressure =
                _steps.Where(i => i.Status[StatusName.燃料油阀门] == open)
                    .OrderByDescending(i => i.Status[StatusName.再生器压力])
                    .ThenByDescending(i => i.Date)
                    .FirstOrDefault();
            //var fueloil_open_item = _steps.Where(i => i.Status[StatusName.燃料油阀门] == open).OrderBy(i => i.Date).FirstOrDefault();
            //var avg_presscharringtank_count = _steps.Count(i => i.Status[StatusName.燃料油阀门] == open);
            //var avg_presscharringtank = avg_presscharringtank_count > 0 ? _steps.Where(i => i.Status[StatusName.燃料油阀门] == open && i.Status[StatusName.空气阀门] == open)
            //    .Average(i => i.Status[StatusName.烧焦罐压力]) : -1;
            //1.3空气流量 380-500
            var air_open_item = _steps.Where(i => i.Status[StatusName.空气阀门_主风机_右] == open)
                .OrderBy(i => i.Date).FirstOrDefault();
            var avg_flowair_count = _steps.Count(i => i.Status[StatusName.空气阀门_主风机_右] == open);
            var avg_flowair = avg_flowair_count > 0
                ? _steps.Where(i => i.Status[StatusName.空气阀门_主风机_右] == open)
                    .Average(i => i.Status[StatusName.主风机流量])
                : -1;
            var airFlowValue =
                _steps.Where(i => i.Status[StatusName.空气阀门_主风机_右] == open && i.Status[StatusName.是否进入再生阶段] == 0)//非再生阶段
                    .OrderByDescending(i => i.Status[StatusName.主风机流量] )
                    .ThenByDescending(i => i.Date)
                    .FirstOrDefault();
            var airFlowValue2 =
                _steps.Where(i => i.Status[StatusName.空气阀门_主风机_右] == open)
                    .OrderByDescending(i => i.Status[StatusName.主风机流量])
                    .LastOrDefault();
            Console.WriteLine(airFlowValue == airFlowValue2);

            //1.4 再生器温度 [500,550]
            var avg_tempregenerator_count =
                _steps.Count(i => i.Status[StatusName.燃料油阀门] == open || i.Status[StatusName.空气阀门_主风机_右] == open);
            var avg_tempregenerator = avg_tempregenerator_count > 0
                ? _steps.Where(i => i.Status[StatusName.燃料油阀门] == open
                                    || i.Status[StatusName.空气阀门_主风机_右] == open).Average(i => i.Status[StatusName.再生器温度])
                : -1;

            var tempgenerator =
                _steps.Where(
                    i =>
                        (i.Status[StatusName.燃料油阀门] == open || i.Status[StatusName.空气阀门_主风机_右] == open) &&
                        i.Status[StatusName.再生器温度] > 500 && i.Status[StatusName.再生器温度] < 550)
                    .OrderByDescending(i => i.Date)
                    .FirstOrDefault();


            //1.5 催化剂温度（>700）
            var catalysis_temper_item =
                _steps.Where(i => i.Status[StatusName.催化剂阀门] == open)
                    .OrderByDescending(i => i.Status[StatusName.再生器温度])
                    .ThenByDescending(i => i.Date)
                    .FirstOrDefault();

            //2 反应系统
            //2.1 提升管反应器温度
            var avg_risereactor_count =
                _steps.Count(i => i.Status[StatusName.混合油阀门] == open && i.Status[StatusName.水蒸气阀门] == open &&
                                  i.Status[StatusName.再生催化剂流入提升反应器阀门_再生滑阀] == open);
            var avg_risereactor = avg_risereactor_count > 0
                ? _steps.Where(i => i.Status[StatusName.混合油阀门] == open && i.Status[StatusName.水蒸气阀门] == open &&
                                    i.Status[StatusName.再生催化剂流入提升反应器阀门_再生滑阀] == open)
                    .Average(i => i.Status[StatusName.提升管反应器温度])
                : -1;

            var riserReactorTemp =
                _steps.Where(i => i.Status[StatusName.混合油阀门] == open && i.Status[StatusName.水蒸气阀门] == open &&
                                  i.Status[StatusName.再生催化剂流入提升反应器阀门_再生滑阀] == open)
                    .OrderByDescending(i => i.Date)
                    .FirstOrDefault();

            //2.2 沉降室压力(汽提蒸汽阀，引风机，油焦下放阀同时打开，控制其压力)
            var avg_presetchamber_count = _steps.Count(i => i.Status[StatusName.汽提蒸汽阀门] == open);
            var avg_presetchamber = avg_presetchamber_count > 0
                ? _steps.Where(i => i.Status[StatusName.汽提蒸汽阀门] == open).Average(i => i.Status[StatusName.沉降室压力])
                : -1;

            var presetchamberPressure =
                _steps.Where(i => i.Status[StatusName.汽提蒸汽阀门] == open || i.Status[StatusName.引风机阀门] == open)
                    .OrderByDescending(i => i.Date)
                    .FirstOrDefault();

            //3 再生系统
            //汽提催化阀门
            var stripperCatalystOpenItem = presetchamberPressure != null
                ? _steps.LastOrDefault(
                    i => i.Status[StatusName.沉降室流入烧焦罐阀门_待生滑阀] == open && i.Date > presetchamberPressure.Date)
                : null;

            //外取热器阀门
            var regCatalystOpenItem = presetchamberPressure != null
                ? _steps.LastOrDefault(
                    i => i.Status[StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀] == open && i.Date > presetchamberPressure.Date)
                : null;

            //空气流量
            var airFlowSecondOpenItem = _steps.LastOrDefault(i => i.Status[StatusName.空气阀门_主风机_右] == open);
            //:null 后续判断？

            //反应后的压力或温度
            var reactionLastItem =
                _steps.LastOrDefault(
                    i => i.Status[StatusName.沉降室流入烧焦罐阀门_待生滑阀] == open || i.Status[StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀] == open);






            //3.1主风流量（油焦反应时）         
            var avg_flowair1_count =
                _steps.Count(i => i.Status[StatusName.空气阀门_主风机_右] == open && i.Status[StatusName.再生催化剂流入烧焦罐阀门] == open);
            var avg_flwair1 = avg_flowair1_count > 0
                ? _steps.Where(i => i.Status[StatusName.空气阀门_主风机_右] == open && i.Status[StatusName.再生催化剂流入烧焦罐阀门] == open)
                    .Average(i => i.Status[StatusName.主风机流量])
                : -1;



            //3.2烧焦罐压力(油焦反应时)
            var avg_presschartank1_count =
                _steps.Count(
                    i => i.Status[StatusName.再生催化剂流入烧焦罐阀门] == open && i.Status[StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀] == open
                         && i.Status[StatusName.燃料油阀门] == open && i.Status[StatusName.空气阀门_主风机_右] == open);
            var avg_presschartank1 = avg_presschartank1_count > 0
                ? _steps.Where(
                    i => i.Status[StatusName.再生催化剂流入烧焦罐阀门] == open && i.Status[StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀] == open
                         && i.Status[StatusName.燃料油阀门] == open && i.Status[StatusName.空气阀门_主风机_右] == open)
                    .Average(i => i.Status[StatusName.烧焦罐压力])
                : -1;
            //3.3再生器温度（反应时）
            var avg_tempregenerator1 = avg_presschartank1_count > 0
                ? _steps.Where(
                    i => i.Status[StatusName.再生催化剂流入烧焦罐阀门] == open && i.Status[StatusName.再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀] == open
                         && i.Status[StatusName.燃料油阀门] == open && i.Status[StatusName.空气阀门_主风机_右] == open)
                    .Average(i => i.Status[StatusName.再生器温度])
                : -1;
            //4阀门顺序
            //4.1 燃料油阀门打开
            //var fueloil_open_item = _steps.Where(i => i.Status[StatusName.燃料油阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            //4.2  空气阀门打开
            //var air_open_item 
            //=_steps.Where(i => i.Status[StatusName.空气阀门] == open )
            //    .OrderBy(i => i.Date).FirstOrDefault();
            //4.3 催化剂进料阀门打开
            var catalysis_open_item = _steps.Where(i => i.Status[StatusName.催化剂阀门] == open)
                .OrderBy(i => i.Date).FirstOrDefault();


            #endregion

            #region 计算分数

            #region 预热准备

            //1.预热准备
            //1.1 外取热器上水 液位240-360
            if (level_cold_item != null)
            {
                var level_cold = level_cold_item.Status[StatusName.外取热器液位];
                if (level_cold > _exCooler_level_warning)
                {
                    AddCompose("冷却水上水：液位过高");
                }
                else if (level_cold >= 420 && level_cold<=_exCooler_level_warning)
                {
                    AddCompose("冷却水上水：液位正常在70%以上");
                }
                else if (level_cold < 420)
                {
                    AddCompose("冷却水上水：液位低于70%");
                }
            }
            else
            {
                AddCompose("冷却水上水：未操作");
            }
            //1.2 烧焦罐压力  [0.2-0.4]
            if (regenerPressure != null)
            {
                var value = Math.Round(regenerPressure.Status[StatusName.再生器压力],2);
                if (value >= 0.2 && value <= 0.4)
                {
                    AddCompose("开炉：再生器压力在正常范围：0.2-0.4MPa");
                }
                else if (value < 0.2)
                {
                    AddCompose("开炉：再生器压力低于0.2Mpa");
                }
                else
                {
                    AddCompose("开炉：再生器压力大于0.4Mpa");
                }
            }
            else
            {
                AddCompose("开炉：再生器压力控制未操作");
            }
            //1.3 风机流量
            if (airFlowValue != null)
            {
                var value = airFlowValue.Status[StatusName.主风机流量];
                if (value >=380 && value <= 550)
                {
                    AddCompose("开工阶段主风机打开：主风量在正常范围380-550m3/h");
                }
                else if (value < 380)
                {
                    AddCompose("开工阶段主风机打开：主风量在小于380m3/h");
                }
                else
                {
                    AddCompose("开工阶段主风机打开：主风量大于500m3/h");
                }
            }
            else
            {
                AddCompose("开工阶段主风机打开：未操作");
                
            }
            //1.4 再生器温度[500,550]
            if (tempgenerator != null)
            {
                var value = tempgenerator.Status[StatusName.再生器温度];
                if (value > 500 && value < 550)
                {
                    AddCompose("催化剂原料上料：再生器温度在正常范围500-550℃");
                }
                else if (value < 500)
                {
                    AddCompose("催化剂原料上料：再生器温度低于500℃");
                }
                else
                {
                    AddCompose("催化剂原料上料：再生器温度高于550℃");
                }
            }
            else
            {
                AddCompose("催化剂原料上料：未操作");
            }
            //1.5催化剂温度（>700）
            if (catalysis_temper_item != null)
            {
                var catalysis_temper = catalysis_temper_item.Status[StatusName.再生器温度];
                if (catalysis_temper > 700)
                {
                    AddCompose("催化剂参与反应：温度正常在700℃以上");
                }
                else
                {
                    AddCompose("催化剂参与反应：温度小于700℃");
                }
            }
            else
            {
                AddCompose("催化剂参与反应：未操作");
            }
            #endregion

            #region 反应部分

            //2反应部分
            //2.1 提升管温度
            if (riserReactorTemp != null)
            {
                var value = riserReactorTemp.Status[StatusName.提升管反应器温度];
                if (value > 400 && value < 500)
                {
                    AddCompose("反应进行：提升管温度在正常范围400-500℃");
                }
                else if (value < 400)
                {
                    AddCompose("反应进行：提升管温度低于400℃");
                }
                else
                {
                    AddCompose("反应进行：提升管温度高于500℃");
                }
            }
            else
            {
                AddCompose("反应进行：提升管升温 未操作");
            }
            //2.2 汽提段压力 [0.1-0.2]
            if (presetchamberPressure != null)
            {
                var value =Math.Round( presetchamberPressure.Status[StatusName.沉降室压力],2);
                if (value >= 0.1 && value <= 0.2)
                {
                    AddCompose("反应进行：沉降室压力在正常范围0.1-0.2MPa");
                }
                else if (value > 0.2)
                {
                    AddCompose("反应进行：沉降室压力高于0.2MPa");
                }
                else
                {
                    AddCompose("反应进行：沉降室压力小于0.10MPa");
                }
            }
            else
            {
                AddCompose("反应进行：沉降室压力控制 未操作");
            }
            #endregion

            #region 再生部分
            //3.再生部分
            //3.1 主风量
            if (airFlowSecondOpenItem != null && _isInRegenerate)
            {
                var valur = airFlowSecondOpenItem.Status[StatusName.主风机流量];
                if (valur >= 1000 && valur <= 1200)
                {
                    AddCompose("再生过程：主风量在正常范围1000-1200m3/h");
                }
                else if (valur < 1280)
                {
                    AddCompose("再生过程：主风量小于1000m3/h");
                }
                else
                {
                    AddCompose("再生过程：主风量大于1200m3/h");
                }

                var temp = airFlowSecondOpenItem.Status[StatusName.再生器温度];
                if (temp >= 650 && temp <= 850)
                {
                    AddCompose("再生过程：再生器温度在正常范围650-850℃");
                }
                else if (temp < 650)
                {
                    AddCompose("再生过程：再生器温度低于600℃");
                }
                else
                {
                    AddCompose("再生过程：再生器温度高于850℃");
                }
            }
            else
            {
                AddCompose("再生过程：再生器温度控制未操作");
            }
            //3.2反应后的压力
            if (reactionLastItem != null && _isInRegenerate)
            {
                var value =Math.Round( reactionLastItem.Status[StatusName.再生器压力],2);
                if (value >= 0.4 && value <= 0.6)
                {
                    AddCompose("再生过程：再生器压力在正常范围0.4-0.6MPa");
                }
                else if (value < 0.4)
                {
                    AddCompose("再生过程：再生器压力小于0.4MPa");
                }
                else
                {
                    AddCompose("再生过程：再生器压力大于0.6MPa");
                }
            }
            else
            {
                AddCompose("再生过程：再生器压力控制 未操作");
            } 
            #endregion

            #endregion

        }

        #endregion

        #region 写串口数据

        /// <summary>
        /// 写再生器压力
        /// </summary>
        /// <param name="v"></param>
        void SpReactorPressureValue(double v)
        {
            WritePressureValue(_ylcmd, v);
        }

        /// <summary>
          /// 写入沉降室压力AI id=2
          /// </summary>
          /// <param name="v"></param>
        private void SpSettlingChamberPressure(double v)
        {
            WriteAIvalue(_aicmd, 2, v);
        }

        /// <summary>
        /// 写入提升管温度 AIid=1
        /// </summary>
        /// <param name="v"></param>
        private void SpRiserReactorTemp(double v)
        {
            WriteAIvalue(_aicmd, 1, v);
        }

        /// <summary>
        /// 写再生器温度
        /// </summary>
        /// <param name="v"></param>
        void SpReactorTemp(double v)
        {
            WriteAIvalue(_aicmd, 3, v);
        }

 
        private void SPYWValue(double value)
        {
            if (Isinner) return;
            double write_value = 255 * value/3 / 600;
            write_value = Math.Round(write_value, 0);
            string cmdvalue = write_value.ToString().PadLeft(3, '0');
            string cmd = string.Format(_ywcmd, cmdvalue);
            if (_serialPort.IsOpen)
            {
                lock (this)
                {
                    Thread.Sleep(120);
                    _serialPort.Write(cmd);
                }
            }
        }

        #endregion
        #region 操作继电器
        /// <summary>
        /// 写继电器
        /// </summary>
        /// <param name="number">0-128， </param>
        void SPWriteTool(int number)
        {
            if (Isinner) return;
            WriteTool(_relaycmd, number);
        }
        /// <summary>
        /// 关闭所有继电器
        /// </summary>
        void CloseAllRelay()
        {
            SPWriteTool(0);
        }

        /// <summary>
        /// 开始预警
        /// </summary>
        /// <param name="type">预警类型</param>
        void BeginWarning(WarningType type)
        {
            if (!_warningtypes.Contains(type))
            {
                _flashWarningItem.Open();
                _warningtypes.Add(type);
                _relay_command = _relay_command | _warningnumber;
                SPWriteTool(_relay_command);
            }
        }

        void StopWarning(WarningType type)
        {
            if (_warningtypes.Contains(type))
            {
              _flashWarningItem.Close();
                _relay_command = (~_warningnumber) & _relay_command;
                SPWriteTool(_relay_command);
                _warningtypes.Remove(type);
            }
        }

        /// <summary>
        /// 开始泄漏
        /// </summary>
        void BeginLeak()
        {
            _flashWarningItem.Open();
            _relay_command = _relay_command | _fognumber;
            SPWriteTool(_relay_command);
            Thread.Sleep(500);
            StopLeak();

        }
        /// <summary>
        /// 停止泄漏
        /// </summary>
        void StopLeak()
        {
            _flashWarningItem.Close();
            _relay_command = _relay_command & (~_fognumber);
            SPWriteTool(_relay_command);
        }

        void BeginRightStir()
        {
            _relay_command = _relay_command | _stirnumber2;
            SPWriteTool(_relay_command);
        }

        void StopRightStir()
        {
            _relay_command = _relay_command & (~_stirnumber2);
            SPWriteTool(_relay_command);
        }

        void BeginLeftStir()
        {
            _relay_command = _relay_command | _stirnumber1;
            SPWriteTool(_relay_command);
        }

        void StopLeftStir()
        {
            _relay_command = _relay_command & (~_stirnumber1);
            SPWriteTool(_relay_command);
        }

        void BeginStir(Fan fan)
        {
            if(fan== Fan.left)
                _relay_command = _relay_command | _stirnumber1;
            else
                _relay_command = _relay_command | _stirnumber2;
            SPWriteTool(_relay_command);
        }

        void StopStir(Fan fan)
        {
            if (fan == Fan.left)
                _relay_command = _relay_command & (~_stirnumber1);
            else
                _relay_command = _relay_command & (~_stirnumber2);
            SPWriteTool(_relay_command);
        }
        #endregion
        #region 枚举
        enum Fan
        {
            left,
            right
        }
        enum FieldName
        {
            //阀门
            ValveInStrippedVapor,
            ValveInCatalyst,
            ValveInMixedOil,
            ValveInSteam,
            ValveStrippedCatalyst,
            ValveInAir,
            ValveRiserReactorCatalyst,
            ValveCharringTankCatalyst,
            ValveExternalCoolerCatalyst,
            ValveRegCatalyst,
            ValveInFuelOil,
            ValveInCold,
            ValveDraftFan,
            //管道
            FlowStrippedVapor,
            FlowInCatalyst,
            FlowInMixedOil,
            FlowStrippedCatalyst,
            FlowInAir,
            FlowRiserReactorCatalyst,
            FlowCharringTankCatalyst,
            FlowExternalCoolerCatalyst,
            FlowRegCatalyst,
            FlowInSteam,
            FlowInFuelOil,
            FlowInCold,
            FlowOutAir,
            //标签
            LabelPressureSettlingChamber,
            LabelPressureCharringTank,
            LabelTempRiserReactor,
            LabelFlowAir,
            LabelTempRegenerator,
            LabelPressureRegenerator,
            LabelLevel,
            //闪烁
            FlashPressureSettlingChamber,
            FlashlPressureCharringTank,
            FlashTempRiserReactor,
            FlashFlowAir,
            FlashTempRegenerator,
            FlashPressureRegenerator,
            FlashPressurExCooler,
            FlashWarning

        }
        enum StatusName
        {
            汽提蒸汽阀门,
            催化剂阀门,
            混合油阀门,
            水蒸气阀门,
            汽提催化剂阀门,
            空气阀门_主风机_右,
            再生催化剂流入提升反应器阀门_再生滑阀,
            再生催化剂流入烧焦罐阀门,
            再生催化剂流入外取热器阀门,
            再生催化剂从外取热器流入烧焦罐阀门_外取热器下滑阀,
           沉降室流入烧焦罐阀门_待生滑阀,
            沉降室压力,
            烧焦罐压力,
            提升管反应器温度,
            主风机流量,
            再生器温度,
            再生器压力,
            外取热器液位,
            燃料油阀门,
            冷却水阀门,
            引风机阀门,
            是否进入再生阶段


        }
        enum WarningType
        {
            沉降器压力过高,
            液位过高,
            温度异常,
            压力异常,
            泄漏,
        }
        #endregion

    }
}
